﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace HRProject.Code.DAO
{
    public class BaseDAO
    {
        private DataSource dataSource;

        public BaseDAO()
        {
            this.dataSource = new DataSource();
        }

        public DataTable select(string command, List<BaseCondition> conditions)
        {
            List<SqlParameter> paramCollection = new List<SqlParameter>();
            for (int i = 0; i < conditions.Count; i++)
            {
                SqlParameter param = new SqlParameter(conditions[i].ParamName, conditions[i].ParamValue);
                param.Direction = conditions[i].Direction;
                paramCollection.Add(param);
            }
            return this.dataSource.ExecuteQuery(command, paramCollection, false);
        }

        protected int update(string command, List<BaseCondition> conditions)
        {
            List<SqlParameter> paramCollection = new List<SqlParameter>();
            List<int> outIndices = new List<int>();
            for (int i = 0; i < conditions.Count; i++)
            {
                SqlParameter param = new SqlParameter(conditions[i].ParamName, conditions[i].ParamValue);
                param.Direction = conditions[i].Direction;
                paramCollection.Add(param);
                if (conditions[i].Direction.Equals(ParameterDirection.Output))
                    outIndices.Add(i);
            }
            int result = this.dataSource.Execute(command, paramCollection, true);
            for (int i = 0; i < outIndices.Count; i++)
            {
                conditions[outIndices[i]].ParamValue = paramCollection[outIndices[i]].Value;
            }
            return result;
        }
    }
}
